package com.zhsj.OkeHomeConsumption.ui.fragment.minehome;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.popview.OptionPicker;
import com.zhsj.OkeHomeConsumption.ui.activity.MineUserAuthFragment;
import com.zhsj.OkeHomeConsumption.ui.activity.bussiness.InviteQRcodeActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ProgressDrawableAlertDialog;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

import static com.zhsj.OkeHomeConsumption.ui.activity.wallet.BaseFragment.isFastDoubleClick;

/**
 * 个人中心页面
 */
public class MessageActivity extends MyActivity implements View.OnClickListener {

    /**
     * @Fields name_ed : TODO 真实填写
     */
    private EditText name_ed = null;

    // 去实名认证
    private RelativeLayout relativeLayout_realnameauth;
    // 未认证
    private TextView realnameauth_tv;
    /**
     * @Fields person_phonenum_ed : TODO 修改手机号
     */
    private EditText person_phonenum_ed = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;
    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * @Fields mPreferanceUtils : TODO 数据存储工具类
     */
    private SharedPreferanceUtils mSharedPreferanceUtils = null;

    private FormalUserInfo formalUserInfo = null;

    private Bundle mCallBackBundle;
    private RelativeLayout lin;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message;
    }

    @Override
    protected int getTitleId() {
        return R.id.title;
    }

    @Override
    protected void initView() {
        // 初始化本页数据
        name_ed = (EditText) findViewById(R.id.name_ed);
        person_phonenum_ed = (EditText) findViewById(R.id.person_phonenum_ed);
        person_phonenum_ed.setInputType(InputType.TYPE_NULL);
        relativeLayout_realnameauth = (RelativeLayout) findViewById(R.id.relativeLayout_realnameauth);
        realnameauth_tv = (TextView) findViewById(R.id.realnameauth_tv);
        lin = findViewById(R.id.relativeLayout_personsex);
    }

    @Override
    protected void initData() {
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(getActivity());
        mSharedPreferanceUtils = new SharedPreferanceUtils(getActivity());
        mCallBackBundle = new Bundle();
        addLinstener();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 个人信息查询异步请求类
        UserDetailThread();
    }

    /**
     * @Title: addLinstener @Description: TODO 添加视图监听器 @param @return void
     * 返回类型 @throws
     */
    protected void addLinstener() {
        // TODO Auto-generated method stub
        relativeLayout_realnameauth.setOnClickListener(this);
        lin.setOnClickListener(this);
        // 手机号
        person_phonenum_ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    String phonenumStr = person_phonenum_ed.getText().toString().trim();
                    // 修改手机号
                    ModifyMobileThread(phonenumStr);
                    return true;
                }
                return false;
            }
        });
        // 昵称
        name_ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    String nickName = name_ed.getText().toString().trim();
                    ModifyNickNameThread(nickName);
                    return true;
                }
                return false;
            }
        });

    }

    /**
     * @Title: selectSex @Description: TODO @param @return void 返回类型 @throws
     */


    /**
     * @Title: UserDetailThread @Description: TODO 个人信息查询 @param @return void
     * 返回类型 @throws
     */
    public void UserDetailThread() {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("UserDetailThread sign = ", Constants.SIGN);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        HttpClient.get(OkeHomeConsumptionApi.ELVDOU_DETAIL, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                LogUtils.e("个人信息", "" + content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // showShortToast("个人信息查询成功");
                        JSONObject optJSONObject = jsonOBJ.optJSONObject("data");
                        formalUserInfo = JsonUtils.object(optJSONObject.toString(), FormalUserInfo.class);


                        // 设置手机号
                        person_phonenum_ed.setText(formalUserInfo.getMobile());
                        if (formalUserInfo.getUserAuthentic() == null) {
                            // 未认证
                            realnameauth_tv.setText("未认证");
                            realnameauth_tv.setTextColor(Color.RED);
                            name_ed.setEnabled(true);
                            // 设置昵称
                            name_ed.setText(formalUserInfo.getName());
                        }
                        if (formalUserInfo.getUserAuthentic().isAuthenticated()) {
                            // 已认证
                            realnameauth_tv.setText("已认证");
                            realnameauth_tv.setTextColor(Color.GREEN);
                            name_ed.setEnabled(true);
                            // 设置昵称
                            name_ed.setText(formalUserInfo.getName());
                        } else {
                            // 未认证
                            realnameauth_tv.setText("未认证");
                            realnameauth_tv.setTextColor(Color.RED);
                            name_ed.setEnabled(true);
                            // 设置昵称
                            name_ed.setText(formalUserInfo.getName());
                        }
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("RegisterActivity", "sendcode异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * @Title: ModifySexThread @Description: TODO @param @param sex @return void
     * 返回类型 @throws
     */
    public void ModifySexThread(String sex) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        Constants.TIME = URLEntity.getInstance().getT();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mUserModifyHashMap = new HashMap<String, String>();
        mUserModifyHashMap.put("v", Constants.APPVERSION);
        mUserModifyHashMap.put("t", Constants.TIME);
        LogUtils.e("UserModifyThread time =", Constants.TIME);
        mUserModifyHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mUserModifyHashMap.put("platform", Constants.PLAFORM);
        mUserModifyHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mUserModifyHashMap.put("client", Constants.CLIENT);
        if (sex.equals("男")) {
            mUserModifyHashMap.put("sex", String.valueOf(1));
            paramMaps.put("sex", String.valueOf(1));
        } else {
            mUserModifyHashMap.put("sex", String.valueOf(2));
            paramMaps.put("sex", String.valueOf(2));
        }
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mUserModifyHashMap);
        LogUtils.e("UserModifyThread sign = ", Constants.SIGN);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_USER_MESSAGE, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                LogUtils.e("UserDetailThread =》onSuccess", "" + content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // showShortToast("修改性别成功");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("ModifySexThread", "修改异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * @Title: ModifyMobileThread @Description: TODO 修改手机号 @param @param
     * mobile @return void 返回类型 @throws
     */
    public void ModifyMobileThread(String mobile) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        Constants.TIME = URLEntity.getInstance().getT();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mUserModifyHashMap = new HashMap<String, String>();
        mUserModifyHashMap.put("v", Constants.APPVERSION);
        mUserModifyHashMap.put("t", Constants.TIME);
        LogUtils.e("UserModifyThread time =", Constants.TIME);
        mUserModifyHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mUserModifyHashMap.put("platform", Constants.PLAFORM);
        mUserModifyHashMap.put("mobile", mobile);
        mUserModifyHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mUserModifyHashMap.put("client", Constants.CLIENT);
        paramMaps.put("mobile", mobile);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mUserModifyHashMap);
        LogUtils.e("UserModifyThread sign = ", Constants.SIGN);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_USER_MESSAGE, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                LogUtils.e("UserDetailThread =》onSuccess", "" + content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // showShortToast("修改手机号成功");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("ModifyMobileThread", "修改异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    /**
     * @Title: ModifyNickNameThread @Description: TODO 修改昵称 @param @param
     * nickName @return void 返回类型 @throws
     */
    public void ModifyNickNameThread(final String nickName) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        Constants.TIME = URLEntity.getInstance().getT();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mModifyNickNameHashMap = new HashMap<String, String>();
        mModifyNickNameHashMap.put("v", Constants.APPVERSION);
        mModifyNickNameHashMap.put("t", Constants.TIME);
        LogUtils.e("UserModifyThread time =", Constants.TIME);
        mModifyNickNameHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mModifyNickNameHashMap.put("platform", Constants.PLAFORM);
        mModifyNickNameHashMap.put("name", nickName);
        mModifyNickNameHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mModifyNickNameHashMap.put("client", Constants.CLIENT);
        paramMaps.put("name", nickName);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mModifyNickNameHashMap);
        LogUtils.e("UserModifyThread sign = ", Constants.SIGN);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_USER_MESSAGE, paramMaps, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                LogUtils.e("ModifyNickNameThread =》onSuccess", "" + content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("msg");
                    if (code.equals("N000000")) {
                        // showShortToast("修改昵称成功");
                        mCallBackBundle.putString("nickname", nickName);
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                        }
                    }
                } catch (JSONException ex) {
                    LogUtils.e("ModifyMobileThread", "修改异常 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.topbar_textview_leftitle:
                if (mCallBackBundle != null) {
                    setResult(RESULT_OK);
                }
                finish();
                break;
            case R.id.relativeLayout_personsex:
                Intent intent7 = new Intent(getActivity(), InviteQRcodeActivity.class)
                        .putExtra("flage", 2);
                startActivity(intent7);
                break;

            case R.id.relativeLayout_realnameauth:
                // 实名认证
                if (isFastDoubleClick()) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putSerializable("formalUserInfo",formalUserInfo);
                Intent intent = new Intent(this, MineUserAuthFragment.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                // 个人信息查询异步请求类
//                UserDetailThread();
                // 实名认证后返回数据
                if (data == null) {
                    return;
                }
                realnameauth_tv.setText(data.getStringExtra("auth"));
                realnameauth_tv.setTextColor(Color.GREEN);
                break;
        }
    }

}
